package com.huanghuai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huanghuai.vo.HttpResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AppAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        HttpResult httpResult = HttpResult.builder()
                .code(0)
                .msg("访问拒绝")
                .build();
        String strResponse = objectMapper.writeValueAsString(httpResult);
        response.setCharacterEncoding("UTF-8");//设置响应字符集
        response.setContentType("application/json;charset=utf-8");//设置响应内容类型
        PrintWriter writer = response.getWriter();//获取书写区
        writer.println(strResponse);
        writer.flush();
    }
}
